package com.jhgsys.internal.common.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

@Component
public class UploadPathUtil {

	private static String uploadRoot;

	@Value("${jebs.upload.root}")
	public void setRootPath(String uploadRoot) {
		UploadPathUtil.uploadRoot = uploadRoot;
	}

	public static String getRootPath() {
		return uploadRoot;
	}

	public static String getRootFilesPath() {
		return uploadRoot + "files/";
	}

	public static String getRootImagesPath() {
		return uploadRoot + "images/";
	}

	/**
	 * 获取应用的根目录，路径分隔符为/，路径结尾无/
	 *
	 * @return
	 */
	public static String getRootPathBak() {

		String rootPath = "";
		String path = UploadPathUtil.class.getResource("UploadPathUtil.class").toString();
		String os = System.getProperty("os.name").toLowerCase();
		try {
			if (os.startsWith("win")) {
				path = URLDecoder.decode(path, "GB2312");
			} else {
				path = URLDecoder.decode(path, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		path.replaceAll("\\\\", "/");
		int index = path.indexOf("WEB-INF");
		if (index == -1) {
			index = path.indexOf("bin");
		}
		if (index == -1) {
			index = path.indexOf("lib");
		}
		if (index == -1) {
			int index2 = path.indexOf("jar!");
			if (index2 != -1) {
				path = path.substring(0, index2);
				System.out.println(path);
				System.out.println(File.separator);
				index = path.lastIndexOf("/");
				System.out.println(index);
			}
		}
		path = path.substring(0, index);
		if (path.startsWith("jar")) {
			path = path.substring(9);
		}
		if (path.startsWith("file")) {
			path = path.substring(5);
		}
//		if (path.endsWith("/") || path.endsWith("\\")) {
//			path = path.substring(0, path.length() - 1);
//		}

		if (os.startsWith("win")) {
			path = path.substring(1);
		}
		rootPath = path;

		return rootPath;
	}
}
